package com.xxlie.auth.security.auth.ajax;

import com.xxlie.auth.domain.User;
import com.xxlie.auth.security.auth.AjaxAuthenticationToken;
import com.xxlie.auth.security.model.UserContext;
import com.xxlie.auth.service.impl.UserServiceImpl;
import com.xxlie.auth.common.CommUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * AjaxAuthenticationProvider
 *
 * @author xxlie.com
 * @since 2017/7/30
 */
@Component
public class AjaxAuthenticationProvider implements AuthenticationProvider {

    private final PasswordEncoder encoder;
    private final UserServiceImpl userService;

    @Autowired
    CommUtil commUtil;

    @Autowired
    public AjaxAuthenticationProvider(final UserServiceImpl userService, final PasswordEncoder encoder) {
        this.userService = userService;
        this.encoder = encoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.notNull(authentication, "No authentication data provided");


        //设置扩展参数
        AjaxAuthenticationToken authenticationToken = (AjaxAuthenticationToken) authentication;
        Map<String, Object> extraParams = authenticationToken.getExtraParams();

        User user = null;
        if (extraParams.get("source").equals(LoginSourceEnum.PC.getCode())) {
            String username = (String) authentication.getPrincipal();
            String password = (String) authentication.getCredentials();

            Optional<User> userOptional = userService.getByUsername(username);
            user = userOptional.orElse(null);
            if (user == null) {
                throw new BadCredentialsException("不存在的账户");
            }
            if (!encoder.matches(password, user.getPassword())) {
                throw new BadCredentialsException("用户名或密码错误");
            }
            if (RoleTypeEnum.OTHER.getCode().equals(user.getRole().getRoleType())) {
                throw new BadCredentialsException("没有后台登录权限");
            }
        } else if (extraParams.get("source").equals(LoginSourceEnum.APP.getCode())) {
            String phone = (String) authentication.getPrincipal();
            String smsCode = (String) authentication.getCredentials();

            Optional<User> users = userService.findByPhone(phone);
            if (users.isPresent()) {
                user = users.get();
            } else {
                throw new InsufficientAuthenticationException("手机号未注册");
            }

            //验证验证码
            Boolean checkResult = commUtil.validateSmsCode(phone, smsCode);
            if (!checkResult) {
                throw new InsufficientAuthenticationException("验证码错误");
            }
        } else {
            String username = (String) authentication.getPrincipal();
            String password = (String) authentication.getCredentials();

            Optional<User> userOptional = userService.getByUsername(username);
            user = userOptional.orElse(null);
            if (user == null) {
                throw new BadCredentialsException("不存在的账户");
            }
            if (!encoder.matches(password, user.getPassword())) {
                throw new BadCredentialsException("用户名或密码错误");
            }
            if (user.getRole().getId() == 1) {
                throw new BadCredentialsException("对不起，权限不足");
            }
        }

        if (user.getRole() == null)
            throw new InsufficientAuthenticationException("User has no role assigned");

        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole().authority()));

        UserContext userContext = UserContext.create(user.getUsername(), authorities);

        userContext.setExtraParams(extraParams);


        return new AjaxAuthenticationToken(userContext, null, userContext.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (AjaxAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
